<template>
  <div class="center">
    <header>
      <BaseNavBar title="个人中心" :is-nav="true" />
    </header>
    <main style="margin-top: 8px;">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field v-model="user.username" label="用户名" readonly />
          <van-field v-model="user.realName" name="realName" label="真实姓名" placeholder="请输入真实姓名" />
          <van-field v-model="user.nickname" name="nickname" label="昵称" placeholder="请输入昵称" />
          <van-field v-model="user.telephone" name="telephone" label="电话" placeholder="请输入电话" />
          <van-field v-model="user.email" name="email" label="邮箱" placeholder="请输入邮箱" />
          <van-field name="sex" label="性别">
            <template #input>
              <van-radio-group v-model="user.sex" direction="horizontal">
                <van-radio :name="1">男</van-radio>
                <van-radio :name="2">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field v-model="user.level" label="会员等级" readonly />
          <van-field v-model="user.points" label="积分"  readonly/>
          <van-field v-model="user.createTime" label="加入时间"  readonly/>
        </van-cell-group>

        <div style="margin: 16px;">
          <van-button round block type="primary" color="#754c29" native-type="submit">
            提交
          </van-button>
          <van-button style="margin-top: 8px;" round block type="primary" plain color="#754c29" @click="handleReset">
              重置
          </van-button>
        </div>
      </van-form>
    </main>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import BaseNavBar from '@/components/BaseNavBar/index.vue';
import { getUserInfo,userUpdate } from '@/apis/user';
import { showToast, showConfirmDialog } from 'vant';

const user = ref({
  username: "",
  realName: "",
  nickname: "",
  telephone: "",
  email: "",
  sex:""
});
const init = async () => {
  try {
    const { data } = await getUserInfo();
    user.value = data;
  } catch (error) {
    console.log(error, 'error');

  }
};

const onSubmit = (values) => {
  showConfirmDialog({
    title: `确定修改当前用户的信息吗？`,
    confirmButtonColor:"#f50"
  })
    .then(async () => {
      try {
        const { code, msg } = await userUpdate(values);
        if (code === 200) {
          showToast('已成功修改');
          init();
          return
        }
        showToast(msg);

      } catch (error) {
        console.log(error, 'error');

      }

    })
    .catch(() => {

    });
};

const handleReset = () => {
  init();
};

onMounted(() => {
  init();
});

</script>

<style lang="less" scoped></style>
